using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Ras2ClassLib;

namespace Ras2
{
	public enum PerformerColumns
	{
		ColName = 0,
		ColDescription = 1,
		NumberOfColumns = 2
	}

	public partial class PerformerView : UserControl
	{
		private SortOrder[] m_arrLastSortOrder = new SortOrder[(int)PerformerColumns.NumberOfColumns];
		private FlytjandiDoc m_document;

		public FlytjandiDoc Document
		{
			get { return m_document; }
			set { m_document = value; }
		}

		public PerformerView()
		{
			InitializeComponent();
		}

		private void OnMenuUpdatePerformer(object sender, EventArgs e)
		{
			OnUpdatePerformer();
		}

		private void OnLoad(object sender, EventArgs e)
		{
			if (!this.DesignMode)
			{
				m_listViewPerformer.Items.Clear();

				FlytjandiDoc doc = new FlytjandiDoc();
				FlytjandiCollection performers = doc.GetAllFlytjandi();

				foreach (Flytjandi performer in performers)
				{
					m_listViewPerformer.Items.Add(GetListViewItem(performer));
				}
			}
		}

		private void OnSortPerformer(object sender, ColumnClickEventArgs e)
		{
			SortOrder lastOrder = m_arrLastSortOrder[e.Column];
			m_arrLastSortOrder[e.Column] = (lastOrder == SortOrder.Ascending) ? SortOrder.Descending : SortOrder.Ascending;
			m_listViewPerformer.ListViewItemSorter = new PerformerSorter((PerformerColumns)e.Column, lastOrder);
		}

		private void OnDoubleClickPerformer(object sender, EventArgs e)
		{
			OnUpdatePerformer();
		}

		private ListViewItem GetListViewItem( Flytjandi performer )
		{
			ListViewItem item = new ListViewItem( performer.Name );

			item.SubItems.Add( performer.Description);

			item.ImageIndex = 0;

			item.Tag = performer;

			return item;
		}

		protected void HandleError( Exception ex )
		{
			MessageBox.Show( "Eftirfarandi villa kom upp: \n\n" + ex.Message );
		}

		public void OnUpdatePerformer()
		{
			try
			{
				if (m_listViewPerformer.SelectedItems.Count == 1)
				{
					ListViewItem listViewItem = m_listViewPerformer.SelectedItems[0];

					Flytjandi performer = (Flytjandi)listViewItem.Tag;

					using (PerformerDlg dlg = new PerformerDlg())
					{
						dlg.Performer = performer;

						if (dlg.ShowDialog() == DialogResult.OK)
						{
							performer = dlg.Performer;

							Document.UpdateFlytjandi(performer);

							int nIndex = listViewItem.Index;
	
							m_listViewPerformer.Items.Remove(listViewItem);
							m_listViewPerformer.Items.Insert(nIndex, GetListViewItem(performer));
						}
					}
				}
			}
			catch (Exception ex)
			{
				HandleError(ex);
			}
		}
	}
}